package moteur;

import java.util.ArrayList;
import java.util.Stack;

public class InputErrorChecker 
{
	public static boolean checkBoolExp(ArrayList<String> inputs)
	{
		boolean state = true;
		
		ArrayList<String> postfix = new ArrayList<String>();
		Stack<String> stack = new Stack<String>();
		try
		{
			for(String str: inputs)
			{
				if(str.equals("(") || str.equals("|"))
				{
					stack.push(str);
				}
				else if(str.equals("&"))
				{
					while(!stack.isEmpty() && (stack.peek().equals("|") && stack.peek().equals("&")))
					{
						postfix.add(stack.pop());
					}
					stack.push(str);
				}
				else if(str.equals(")"))
				{
					while(!stack.isEmpty() && !stack.peek().equals("("))
					{
						postfix.add(stack.pop());
					}
					stack.pop();
				}
				else
				{
					postfix.add(str);
				}
			}
			
			while(!stack.isEmpty())
			{
				postfix.add(stack.pop());
			}
			
			Stack<String> checkStack = new Stack<String>();
			for(int i=0; i<postfix.size(); ++i)
			{
				String str = postfix.get(i);
				if(str.equals("&"))
				{
					checkStack.pop();
					checkStack.pop();
					checkStack.push("x");
				}
				else if(str.equals("|"))
				{
					checkStack.pop();
					checkStack.pop();
					checkStack.push("x");
				}
				else if(str.equals("~"))
				{
					checkStack.push(inputs.get(++i));
				}
				else
				{
					checkStack.push(postfix.get(i));
				}
			}
			
			state = checkStack.size() == 1;
		}
		catch(Exception ex)
		{
			return false;
		}
		
		return state;
	}
	
	public static void main(String[] args)
	{
		String s = "( A & B & ( ~| C ) )";
		String[] inputs = s.split(" ");
		
		ArrayList<String> in = new ArrayList<String>();
		
		for(String i: inputs)
		{
			if(!i.equals(""))
				in.add(i);
		}
		
		System.out.println(checkBoolExp(in));
	}
}
